package com.bw.home

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.bw.home.entity.SimpleTypeEntity
import com.bw.home.entity.SimpleVideoEntity
import com.bw.home.intent.HomeIntent
import com.bw.home.viewmodel.HomeViewModel
import com.bw.lib_common.GlobalValue
import com.bw.lib_common.NavPath
import com.bw.lib_miv.BaseBox
import com.bw.lib_miv.IUiState
import com.bw.lib_miv.RequestType
import com.tencent.mmkv.MMKV
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMWeb
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@Composable
fun HomePage(
    navHostController: NavHostController,
    vm: HomeViewModel = hiltViewModel(),
    scope: CoroutineScope = rememberCoroutineScope()
) {

    val typeList = remember {
        SnapshotStateList<SimpleTypeEntity>()
    }

    var typeState by remember {
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = "", block = {
        scope.launch {
            vm.uiState.collect {
                when (it) {

                    is IUiState.OnSuccess -> {
                        if (it.type == RequestType.SIMPLE_TYPE) {
                            typeList.clear()
                            typeList.addAll(it.data as Collection<SimpleTypeEntity>)
                            Log.d("TagA", "type: $typeList")
                            typeState = true
                        }
                    }

                    is IUiState.OnFailed -> {
                        Log.d("TagA", "获取类型失败")
                    }

                    else -> {}
                }
            }
        }
        vm.sendIntent(HomeIntent.getSimpleType)
    })

    Column(
        Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        BaseBox(title = "首页")

        if (typeState) {
            tabBar(typeList, navHostController = navHostController)
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun tabBar(
    list: List<SimpleTypeEntity>, navHostController: NavHostController
) {
    var selector by remember {
        mutableStateOf(0)
    }

    val pageState = rememberPagerState {
        list.size
    }


    Column(
        Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .padding(5.dp)
    ) {
        ScrollableTabRow(
            selectedTabIndex = selector,
            edgePadding = 16.dp
        ) {
            list.forEachIndexed { index, title ->
                Tab(
                    selected = selector == index,
                    onClick = {
                        selector = index
                    },
                    text = {
                        Text(text = "${title.typename}")
                    }
                )
            }
        }

        HorizontalPager(state = pageState) {
            getVideo(list = list[selector], navHostController = navHostController)
        }
    }
}


@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun getVideo(
    list: SimpleTypeEntity,
    navHostController: NavHostController,
    scope: CoroutineScope = rememberCoroutineScope(),
    vm: HomeViewModel = hiltViewModel()
) {
    val videoList = remember {
        SnapshotStateList<SimpleVideoEntity>()
    }

    scope.launch {
        vm.uiState.collect {
            when (it) {

                is IUiState.OnSuccess -> {
                    if (it.type == RequestType.SIMPLE_VIDEO) {
                        videoList.clear()
                        videoList.addAll(it.data as Collection<SimpleVideoEntity>)
                        Log.d("TagA", "video: $videoList")
                    }
                }

                is IUiState.OnFailed -> {
                    Log.d("TagA", "获取类型失败")
                }

                else -> {}
            }
        }
    }
    vm.sendIntent(HomeIntent.getSimpleVideo(list.channelid, 1, 10))

    //数据
    LazyColumn(Modifier.fillMaxWidth()) {
        items(videoList) {
            homeList(navHostController = navHostController, videoList = it)
        }
    }
}

@Composable
fun homeList(
    navHostController: NavHostController,
    videoList: SimpleVideoEntity,
    vm: HomeViewModel = hiltViewModel()
) {

    val decodeString = MMKV.defaultMMKV().decodeInt("${videoList.id}", 0)
    var buttonText by remember {
        mutableStateOf(
            if (decodeString == 0) {
                "关注"
            } else {
                "已关注"
            }
        )
    }

    var buttonColor by remember {
        mutableStateOf(
            if (decodeString == 0) {
                Color(0xFF673AB7)
            } else {
                Color(0xFF4CAF50)
            }
        )
    }

    Column(
        Modifier
            .fillMaxWidth()
            .padding(5.dp)
    ) {
        Row(
            Modifier
                .fillMaxWidth()
                .height(50.dp), verticalAlignment = Alignment.CenterVertically
        ) {
            AsyncImage(model = videoList.avatar_url, contentDescription = "", Modifier.size(30.dp))

            Column(Modifier.weight(1f), verticalArrangement = Arrangement.Center) {
                Text(text = videoList.name)
                Spacer(modifier = Modifier.height(5.dp))
                Text(text = videoList.ctime)
            }

            Button(onClick = {
                val string = MMKV.defaultMMKV().decodeInt("${videoList.id}", 0)

                if (string == 0) {
                    buttonText = "已关注"
                    buttonColor = Color(0xFF4CAF50)
                    MMKV.defaultMMKV().encode("${videoList.id}", videoList.id)
                    ToastUtils.showLong("关注")
                } else {
                    buttonText = "关注"
                    buttonColor = Color(0xFF673AB7)
                    MMKV.defaultMMKV().encode("${videoList.id}", 0)
                    ToastUtils.showLong("取消关注")
                }
            }, colors = ButtonDefaults.buttonColors(buttonColor)) {
                Text(text = buttonText)
            }
        }

        Box(
            Modifier
                .fillMaxWidth()
                .height(150.dp)
        ) {

            AsyncImage(
                model = videoList.videomainimag,
                contentDescription = "",
                Modifier
                    .fillMaxWidth()
                    .fillMaxHeight(), contentScale = ContentScale.Crop
            )

            Column(
                Modifier
                    .fillMaxWidth()
                    .fillMaxHeight(),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Image(
                    painter = painterResource(id = R.drawable.ic_play),
                    contentDescription = "",
                    alignment = Alignment.Center, modifier = Modifier.clickable {
                        val bool = MMKV.defaultMMKV().decodeBool("login", false)
                        vm.setList(videoList)
                        if (bool) {
                            navHostController.navigate(NavPath.HOME_DETAILS)
                        } else {
                            ToastUtils.showLong("请先登录")
                            navHostController.navigate(NavPath.LOGIN)
                        }
                    }
                )
            }

            Row(
                Modifier
                    .fillMaxWidth()
                    .fillMaxHeight(), verticalAlignment = Alignment.Bottom
            ) {
                Text(
                    text = "23K",
                    Modifier
                        .padding(start = 10.dp, bottom = 10.dp)
                        .background(Color(0xFFBEBABA))
                )
                Column(Modifier.weight(1f)) {

                }
                Text(
                    text = "2分10秒",
                    Modifier
                        .padding(end = 10.dp, bottom = 10.dp)
                        .background(Color(0xFFBEBABA))
                )
            }
        }

        Text(text = videoList.title)

        Row(
            Modifier
                .fillMaxWidth()
                .height(50.dp), verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                Modifier
                    .weight(1f)
                    .fillMaxHeight()
                    .clickable {
                        share(videoList)
                    },
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center
            ) {
                Image(
                    painter = painterResource(id = R.drawable.ic_home_share),
                    contentDescription = ""
                )

                Text(text = "分享", fontSize = 18.sp)
            }

            Row(
                Modifier
                    .weight(1f)
                    .fillMaxHeight(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center
            ) {
                Image(
                    painter = painterResource(id = R.drawable.ic_sms),
                    contentDescription = ""
                )

                Text(text = "20", fontSize = 18.sp)
            }

            val item_id = MMKV.defaultMMKV().decodeString("${videoList.item_id}", "")

            var dianZan by remember {
                mutableStateOf(R.drawable.ic_home_detail_description_agree)
            }

            var num by remember {
                mutableStateOf(videoList.id)
            }

            var itemState by remember {
                mutableStateOf(
                    if (item_id?.isBlank() == true) {
                        dianZan = R.drawable.ic_home_detail_description_agree
                    } else {
                        dianZan = R.drawable.ic_thumb_up_check
                    }
                )
            }

            Row(
                Modifier
                    .weight(1f)
                    .fillMaxHeight()
                    .clickable {
                        val item =
                            MMKV
                                .defaultMMKV()
                                .decodeString("${videoList.item_id}", "")
                        if (item?.isBlank() == true) {
                            num = ++num
                            dianZan = R.drawable.ic_thumb_up_check
                            MMKV.defaultMMKV().encode("${videoList.item_id}",videoList.item_id)
                        } else {
                            num = --num
                            dianZan = R.drawable.ic_home_detail_description_agree
                            MMKV.defaultMMKV().encode("${videoList.item_id}","")
                        }
                    },
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center
            ) {
                Image(
                    painter = painterResource(id = dianZan),
                    contentDescription = ""
                )

                Text(text = "$num", fontSize = 18.sp)
            }
        }
    }
}

fun share(videoList: SimpleVideoEntity) {
    val web: UMWeb = UMWeb(videoList.videopath);
    web.setTitle("This is music title");//标题
    web.setDescription("my description");//描述

    ShareAction(GlobalValue.mainActivity)
        .withMedia(web)
        .open()
}